from rest_framework import serializers

from .models import Inform, InformRead
from apps.oaauth.serializers import UserSerializer, DepartmentSerializer
from ..oaauth.models import OADepartment


class InformReadSerializer(serializers.ModelSerializer):
    class Meta:
        model = InformRead
        fields = '__all__'


class InformSerializer(serializers.ModelSerializer):
    author = UserSerializer(read_only=True)
    departments = DepartmentSerializer(many=True, read_only=True)
    # 包含了部门id的列表
    department_ids = serializers.ListField(write_only=True)
    reads = InformReadSerializer(many=True, read_only=True)

    class Meta:
        model = Inform
        fields = '__all__'
        read_only_fields = ('publish',)

    # 重写保存Inform对象的create方法
    def create(self, validated_data):
        request = self.context.get('request')
        department_ids = validated_data.pop('department_ids')
        # department_ids: ['0', '1', '2', '3']
        department_ids = list(map(lambda value: int(value), department_ids))
        if 0 in department_ids:
            inform = Inform.objects.create(publish=True, author=request.user, **validated_data)
        else:
            departments = OADepartment.objects.filter(id__in=department_ids)
            inform = Inform.objects.create(publish=False, author=request.user, **validated_data)
            inform.departments.set(departments)
            inform.save()
        return inform


    def update(self, instance, validated_data):
        department_ids = validated_data.pop('department_ids')
        department_ids = list(map(int, department_ids))  # 简化类型转换
        instance.departments.clear()

        if 0 in department_ids:
            instance.publish = True
        else:
            instance.publish = False
            for department_id in department_ids:
                instance.departments.add(department_id)
        return super().update(instance, validated_data)

class ReadInformSerializer(serializers.Serializer):
    inform_pk = serializers.IntegerField(error_messages={"required": "请传入inform的id"})
